package com.sbl.bajw.pc.action;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.pc.service.JcaptchaService;
import com.sbl.bajw.util.JsonUtil;

@Controller
@RequestMapping("/Jcaptcha")
public class JcaptchaAction {	
	
	@Resource
	private JcaptchaService service;
	
    public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";  	    
  
    @RequestMapping(value = "/getImage")
    public @ResponseBody String getImage() throws Exception {  
        try {
        	HttpServletResponse response = WebContext.getResponse();
        	
            ServletOutputStream responseOutputStream = response.getOutputStream();  
            
            BufferedImage challenge = service.getImage();  
            
            response.setHeader("Cache-Control", "no-store");  
            response.setHeader("Pragma", "no-cache");  
            response.setDateHeader("Expires", 0);  
            response.setContentType("image/jpeg");  
            
            ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, responseOutputStream);
            responseOutputStream.flush();
            responseOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return null;
    }  	
    
    @RequestMapping(value = "/check")
    public @ResponseBody String check() throws Exception {  
    	String code = RequestUnit.getString("code");
        String result = service.Check(code)+"";
        Map<String, String> map = new HashMap<String, String>();
        map.put("msg", result);
        return JsonUtil.ConvertObjectToJson(map);
    }  	 

}